﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace common_park
{
    class FileUtils
    {
        private static string errMessage;
        public FileUtils()
        {
            errMessage = string.Empty;
        }

        public static string GetErrMessage
        {
            get { return errMessage; }
        }

        /// <summary>
        /// <para>파일 확장자를 가지고 오는것</para>
        /// <para>ex) c:\test\test.txt  => .txt</para>
        /// </summary>
        /// <param name="filePath">파일 전체 경로</param>
        /// <returns>확장자명</returns>
        public static string GetExtName(string filePath, bool flag = false)
        {
            string tmpExt = Path.GetExtension(filePath);

            if(flag)
            {
                tmpExt = tmpExt.Substring(1);
            }

            return tmpExt;
        }

        /// <summary>
        /// <para></para>
        /// <para></para>
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string GetOnlyFileName(string filePath)
        {
            return Path.GetFileNameWithoutExtension(filePath);
        }
        public static string GetFileName(string filePath)
        {
            return Path.GetFileName(filePath);
        } 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string GetDirectoryName(string filePath, bool flag = false)
        {
            string tempString = Path.GetDirectoryName(filePath);

            if(flag)
                tempString += @"\";
            
            return tempString;
        }

        /// <summary>
        /// <para>파일 드라이브명을 제외한 나머지 경로를 가지고 오는 것</para>
        /// <para>ex) c:\test\test.txt = > \test</para>
        /// </summary>
        /// <param name="filePath">전체 파일 경로</param>
        /// <returns>
        /// 파일경로 명
        /// </returns>
        public static string GetOnlyFileDirectory(string filePath)
        {
            string directory = GetDirectoryName(filePath);
            string drive = GetDrive(filePath);
            return directory.Substring(drive.Length - 1);
        }
        public static string GetDrive(string filePath)
        {
            return Path.GetPathRoot(filePath);
        }
        public static string getProgramPath()
        {
            return System.Reflection.Assembly.GetExecutingAssembly().Location;
        }
        public static string getPrgoramDirectory(bool flag = false)
        {
            return GetDirectoryName(getProgramPath(), flag);
        }
        public static bool IsExistFile(string filePath)
        {
            bool bRet = false;
            FileInfo fileInfo = null;
            try
            {
                fileInfo = new FileInfo(filePath);
                bRet = fileInfo.Exists;
            }
            catch (Exception ex)
            {
                errMessage = ex.ToString();
                bRet = false;
            }
            return bRet;
        }
        public static bool IsExistDirectory(string filePath)
        {
            bool bRet = false;
            DirectoryInfo directoryInfo = null;
            try
            {
                directoryInfo = new DirectoryInfo(filePath);
                bRet = directoryInfo.Exists;
            }
            catch (Exception ex)
            {
                errMessage = ex.ToString();
                bRet = false;
            }
            return bRet;
        }

        public static string GetTempFileName()
        {
            return Path.GetTempFileName();
        }

        public static string GetTempPath()
        {
            return Path.GetTempPath();
        }

        public static bool CreateDirectory(string filePath)
        {
            bool bRet = false;
            DirectoryInfo directoryInfo = null;
            try
            {
                directoryInfo = new DirectoryInfo(filePath);
                if (!directoryInfo.Exists)
                    directoryInfo.Create();

                bRet = directoryInfo.Exists;
            }
            catch (Exception ex)
            {
                errMessage = ex.ToString();
                bRet = false;
            }
            return bRet;
        }

        public static bool MoveFile(string srcFile, string dstFile)
        {
            if (DeleteFile(dstFile))
            {
                File.Move(srcFile, dstFile);
                return IsExistFile(dstFile);
            }

            return false;
        }

        public static bool DeleteFile(string srcFile)
        {
            File.Delete(srcFile);

            return IsExistFile(srcFile);
        }

        // .net 4.0(Visual Studio 2010(버전부터 optional parameter
        public static bool DeleteDirectory(string filePath, bool flag = false)
        {
            bool bRet = false;
            DirectoryInfo directoryInfo = null;
            try
            {
                directoryInfo = new DirectoryInfo(filePath);
                directoryInfo.Delete(flag);
                bRet = IsExistDirectory(filePath);
            }
            catch (Exception ex)
            {
                errMessage = ex.ToString();
                bRet = false;
            }
            return bRet;
        }


        /// <summary>
        /// <para>파일 list 가지고 오기</para>
        /// </summary>
        /// <param name="filePath">전체 파일 경로</param>
        /// <param name="contents">파일 list 목록</param>
        /// <param name="extension">검색하는 확장자</param>
        /// <param name="subFolder">하위디렉토리 확인 여부</param>
        /// <returns>파일경로 명</returns>
        
        public static bool GetFolderFileList(string filePath, ref List<string> contents, string extension = "*.*", bool subFolder = false)
        {
            bool bRet = true;

            try
            {
                foreach (string file in Directory.GetFiles(filePath, extension))
                {
                    contents.Add(file);
                }
                
                if(subFolder)
                {
                    foreach (string folder in Directory.GetDirectories(filePath))
                    {
                        GetFolderFileList(folder, ref contents, extension, subFolder);
                    }
                }

            }
            catch(Exception ex)
            {
                errMessage = ex.ToString();
                bRet = false;
            }

            return bRet;
        }

        public static string[] GetFolderFileList(string filePath, string extension = "*.*", bool subFolder = false)
        {
            List<string> tmpFilelist = new List<string>();

            string[] fileList = null;

            if (GetFolderFileList(filePath, ref tmpFilelist, extension, subFolder))
            {
                fileList = new string[tmpFilelist.Count];

                for(int i = 0 ; i < tmpFilelist.Count ; i++)
                {
                    fileList[i] = tmpFilelist[i];
                }
            }
            
            return fileList;
        }
        


        /// <summary>
        /// <para>파일 list 가지고 오기(확장자 패턴을 확인 후 가지고 오기)</para>
        /// </summary>
        /// <param name="filePath">전체 파일 경로</param>
        /// <param name="contents">파일 list 목록</param>
        /// <param name="extension">검색하는 확장자의 패턴(*.txt|*.dat)</param>
        /// <param name="subFolder">하위디렉토리 확인 여부</param>
        /// http://imsoli.blogspot.kr/2012/05/csystemiodirectorygetfiles.html
        /// <returns> 성공 : true 실패 : false </returns>
        public static bool GetFolderFilePathtenList(string filePath, ref List<string> contents, string extension = "*.*", bool subFolder = false)
        {
            bool bRet = true;

            try
            {
                string searchPatterns = extension;
                string[] files = searchPatterns
                   .Split('|')
                   .SelectMany(searchPattern => Directory.GetFiles(filePath, searchPattern)).ToArray();
                foreach (string file in files)
                {
                    contents.Add(file);
                }

                if (subFolder)
                {
                    foreach (string folder in Directory.GetDirectories(filePath))
                    {
                        GetFolderFilePathtenList(folder, ref contents, extension, subFolder);
                    }
                }
            }
            catch (Exception ex)
            {
                errMessage = ex.ToString();
                bRet = false;
            }

            return bRet;
        }

        public static long GetFileSize(string filePath)
        {
            long lRet = 0;
            
            FileInfo fileInfo = null;
            try
            {
                fileInfo = new FileInfo(filePath);
                lRet = fileInfo.Length;
            }
            catch (Exception ex)
            {
                errMessage = ex.ToString();
            }
            return lRet;
        }

        public static bool readFileList(string filePath, ref string contents, Encoding encodeType)
        {
            bool bRet = false;

            contents = string.Empty;

            if (IsExistFile(filePath))
            {
                System.IO.StreamReader reader = null;

                try
                {
                    reader = new System.IO.StreamReader(filePath, encodeType);
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        filePath += line;
                    }
                    bRet = true;
                }
                catch (Exception ex)
                {
                    errMessage = ex.ToString();
                    contents = string.Empty;
                    bRet = false;
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                        reader.Dispose();
                    }
                }
            }


            return bRet;            
        }

        public static bool readFileList(string filePath, ref List<string> contents, Encoding encodeType)
        {
            if (!IsExistFile(filePath))
                return false;

            bool bRet = false;

            System.IO.StreamReader reader = null;

            try
            {
                reader = new System.IO.StreamReader(filePath, encodeType);
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    contents.Add(line);
                }
                bRet = true;

            }
            catch (Exception ex)
            {
                errMessage = ex.ToString();
                bRet = false;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
            }
            return bRet;
        }

        public static bool WriteFile(string filePath, string contents, Encoding encodeType, bool folderMode = true, bool appendMode = false)
        {
            bool bRet = false;

            if (folderMode && !IsExistDirectory(GetDirectoryName(filePath)))
            {
                CreateDirectory(GetDirectoryName(filePath));
            }

            System.IO.StreamWriter writer = null;

            try
            {
                writer = new System.IO.StreamWriter(filePath, appendMode, encodeType);
                writer.WriteLine(contents);
               
                
            }
            catch (Exception ex)
            {
                errMessage = ex.ToString();
                bRet = false;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                }
            }

            if (IsExistFile(filePath))
                bRet = true;

            return bRet;
        }

        public static bool WriteFileList(string filePath, ref List<string> contents, Encoding encodeType, bool folderMode = true, bool appendMode = false)
        {
            bool bRet = false;

            if (folderMode && !IsExistDirectory(GetDirectoryName(filePath)))
            {
                CreateDirectory(GetDirectoryName(filePath));
            }

            System.IO.StreamWriter writer = null;

            try
            {
                writer = new System.IO.StreamWriter(filePath, appendMode, encodeType);

                foreach (string content in contents)
                {
                    writer.WriteLine(content);
                }
            }
            catch (Exception ex)
            {
                errMessage = ex.ToString();
                bRet = false;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                }
            }

            if (IsExistFile(filePath))
                bRet = true;

            return bRet;
        }

        public static bool excuteCommandLine(string cmdLine, Int32 timeout = 5)
        {
            bool bRet = false;

            Process process = null;

            try
            {
                process = new Process();

                process.StartInfo.UseShellExecute = false;
                process.StartInfo.FileName = cmdLine;
                process.StartInfo.CreateNoWindow = true;
                process.Start();
                try
                {
                    process.WaitForInputIdle();
                }
                catch (Exception ex)
                {
                    errMessage = ex.ToString();
                }
                if (timeout != 0)
                    process.WaitForExit(timeout * 60 * 1000);
                else
                    process.WaitForExit();

                if (process.HasExited == true)
                {
                    int nRet = process.ExitCode;
                    //Log4Net.WriteLogMessage("exe return value == " + nRet, logMode.ERROR);
                    if (nRet == 0) bRet = true;
                }
                else
                {
                    if (process.Responding)
                        process.CloseMainWindow();
                    else
                        process.Kill();
                }
            }
            catch (Exception ex)
            {
                errMessage = ex.ToString();
                bRet = false;
            }
            finally
            {
                if (process != null)
                {
                    process.Close();
                    process.Dispose();
                }
            }
            return bRet;
        }

        public static bool excuteCommandLine(string cmdLine, string argument, Int32 timeout = 5)
        {
            bool bRet = false;

            Process process = null;

            try
            {
                process = new Process();

                process.StartInfo.UseShellExecute = false;
                process.StartInfo.FileName = cmdLine;
                process.StartInfo.Arguments = argument;
                process.StartInfo.CreateNoWindow = true;
                process.Start();
                try
                {
                    process.WaitForInputIdle();
                }
                catch (Exception ex)
                {
                    errMessage = ex.ToString();
                }
                if (timeout != 0)
                    process.WaitForExit(timeout * 60 * 1000);
                else
                    process.WaitForExit();

                if (process.HasExited == true)
                {
                    int nRet = process.ExitCode;
                    //Log4Net.WriteLogMessage("exe return value == " + nRet, logMode.ERROR);
                    if (nRet == 0) bRet = true;
                }
                else
                {
                    if (process.Responding)
                        process.CloseMainWindow();
                    else
                        process.Kill();
                }
            }
            catch (Exception ex)
            {
                errMessage = ex.ToString();
                bRet = false;
            }
            finally
            {
                if (process != null)
                {
                    process.Close();
                    process.Dispose();
                }
            }
            return bRet;
        }

        // 수정 해야 함 오류 있음
        public static bool CoryFolder(string srcPath, string dstPath)
        {
            bool bRet = true;
            if (!IsExistDirectory(dstPath))
            {
                CreateDirectory(dstPath);
            }

            if (bRet)
            {
                string[] files = Directory.GetFiles(srcPath);
                string[] folders = Directory.GetDirectories(srcPath);

                try
                {
                    foreach (string file in files)
                    {
                        string tmpSrcFile = file;
                        string tmpDstFile = Path.Combine(dstPath, GetFileName(file));

                        File.Copy(tmpSrcFile, tmpDstFile);
                    }
                }
                catch (Exception ex)
                {
                    errMessage = ex.ToString();
                    bRet = false;
                }

                try
                {
                    foreach (string folder in folders)
                    {
                        string tmpSrcFolder = folder;
                        string tmpDstFolder = Path.Combine(dstPath, GetFileName(folder));
                        //string tmpDstFolder = dstPath + "\\" + GetFileName(folder);

                        bRet = CoryFolder(tmpSrcFolder, tmpDstFolder);
                        if (bRet) break;
                    }
                }
                catch (Exception ex)
                {
                    errMessage = ex.ToString();
                    bRet = false;
                }

               
            }
            return bRet;
        }
    }
}